/**
 * @Title: model.js
 * @Description: model
 * @author: Fanchao
 * @date: 2020/9/19 7:50 下午
 * @version V1.0
 */

import { pathToRegexp } from 'path-to-regexp';
import { message } from 'antd';
import {
    reqShopList,
} from 'api/index';

export default {
    namespace: 'ShopList',
    state: {
        dataSource: {},
        keyword: '',
        limit: 10,
        offset: 0,
    },
    reducers: {
        setShopList(state, { payload: { dataSource, keyword, limit, offset } }) {
            return { ...state, dataSource, keyword, limit, offset };
        },
    },
    effects: {
        * getShopList({ payload }, { call, put, select }) {
            const result = yield call(reqShopList, payload);
            if (result.status === 1) {
                const dataSource = result.data;
                yield put({
                    type: 'setShopList',
                    payload: {
                        dataSource,
                        keyword: payload.keyword,
                        limit: payload.limit,
                        offset: payload.offset,
                    },
                });
            } else {
                message.error(result.message);
            }
        },
    },
    subscriptions: {
        setup({ dispatch, history }) {
            history.listen(({ pathname }) => {
                if (pathToRegexp('/shop-manage/shop/list').exec(pathname)) {
                    dispatch({
                        type: 'getShopList',
                        payload: {
                            keyword: '',
                            limit: 10,
                            offset: 0,
                        },
                    });
                }
            });
        },
    },
};
